﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Web.Configuration;

namespace ReferralTracker.Helpers {
    public class WebInfo {

        public static string GetIpAddress(HttpRequestBase request) {
            var userIpAddress = "0.0.0.0";

            try {
                var xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];

                if (string.IsNullOrEmpty(xForwardedFor)) {
                    userIpAddress = request.UserHostAddress;
                }
                else {
                    var publicForwardingIps = xForwardedFor.Split(',')
                                                .Where(ip => !IsPrivateIpAddress(ip))
                                                .ToList();
                    userIpAddress = publicForwardingIps.Any() ? publicForwardingIps.Last() : request.UserHostAddress;
                }
            }
            catch (Exception) {
                userIpAddress = "0.0.0.0";
            }

            return userIpAddress;
        }

        public static string GetIpAddress(HttpRequestMessage request) {
            var context = ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request;

            return GetIpAddress(context);
        }

        private static bool IsPrivateIpAddress(string ipAddress) {
            var ip = IPAddress.Parse(ipAddress);
            var octets = ip.GetAddressBytes();

            var is24BitBlock = octets[0] == 10;
            if (is24BitBlock) return true;

            var is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
            if (is20BitBlock) return true;

            var is16BitBlock = octets[0] == 192 && octets[1] == 168;
            if (is16BitBlock) return true;

            var isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
            return isLinkLocalAddress;
        }

        public static bool IsUrlValid(string path) {
            var retVal = false;

            try {
                var request = WebRequest.Create(path);

                request.Timeout = 3000;
                request.GetResponse();
                retVal = true;
            }
            catch (Exception) {
            }

            return retVal;
        }

        public static string GetRegisterReferralUrl(HttpRequestBase request, string referralId) {
            var root = request.Url.GetLeftPart(UriPartial.Authority);
            var registerLinkTemplate = WebConfigurationManager.AppSettings["RegisterReferralLink"];
            var registerLink = registerLinkTemplate
                .Replace("{root}", root)
                .Replace("{referralid}", referralId);

            return registerLink;
        }

    }
}